<template>
  <div class="inventory-check-add-view">
    <el-card class="form-card">
      <div class="form-header">
        <span class="form-title">新增盘点单</span>
      </div>

      <!-- 主表信息 -->
      <el-form
        ref="formRef"
        :model="form"
        label-width="120px"
        class="main-form"
      >
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="盘点单号" prop="inventoryCode">
              <el-input
                v-model="form.inventoryCode"
                placeholder="系统自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盘点类型" prop="inventoryType">
              <el-select
                v-model="form.inventoryType"
                placeholder="请选择盘点类型"
                class="custom-select"
                style="width: 100%"
              >
                <el-option label="产品盘点" value="产品盘点" />
                <el-option label="库位盘点" value="库位盘点" />
                <el-option label="区域盘点" value="区域盘点" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联订单号">
              <el-input
                v-model="form.orderCode"
                placeholder="请输入关联订单号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="制单人">
              <el-input v-model="form.createUseName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="制单日期" prop="createDate">
              <el-date-picker
                v-model="form.createDate"
                type="date"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.notes"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 明细表格 -->
      <div class="detail-section">
        <div class="detail-header">
          <span class="detail-title">盘点明细</span>
          <el-button type="primary" @click="fetchProductOptions"
            >新增产品</el-button
          >
        </div>

        <el-table
          :data="detailList"
          border
          style="width: 100%"
          @selection-change="handleDetailSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productNumber" label="产品编码" width="120" />
          <el-table-column prop="productName" label="产品名称" width="150" />
          <el-table-column prop="specifications" label="规格" width="120" />
          <el-table-column prop="batch" label="批次" width="120" />
          <el-table-column prop="systemQuantity" label="单位" width="100" />
          <el-table-column prop="positionName" label="库位" width="120" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button type="text" @click="removeProduct(scope.$index)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
    </el-card>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="showProductDialog" title="选择产品" width="80%">
      <!-- 查询区域 -->
      <div style="margin-bottom: 10px; display: flex; align-items: center">
        <el-input
          v-model="searchForm.product_Number"
          placeholder="请输入编码"
          style="width: 180px; margin-right: 10px"
        />
        <el-input
          v-model="searchForm.product_Name"
          placeholder="请输入名称"
          style="width: 180px; margin-right: 10px"
        />
        <el-button type="primary" @click="fetchProductOptions">搜索</el-button>
      </div>
      <!-- 商品表格 -->
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="product_Number" label="产品编码" />
        <el-table-column prop="product_Name" label="产品名称" />
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="category_Name" label="类别" />
        <el-table-column prop="storage_Unit" label="存储单位" />
        <el-table-column prop="packaging_Type" label="包装类型" />
        <el-table-column prop="price" label="单价" />
        <el-table-column prop="weight" label="重量" />
      </el-table>
      <table>
        <tr>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, sizes"
              :total="pageQuery1.totalCount"
            >
              共{{ pageQuery1.totalCount }}条 每页显示{{
                pageQuery1.pagesize
              }}条 当前第{{ pageQuery1.pageindex }}页/共{{
                pageQuery1.totalPage
              }}页
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot, prev, pager, next"
              :total="pageQuery1.totalCount"
              prev-text="上一页"
              next-text="下一页"
            >
              <el-button
                :disabled="pageQuery1.pageindex == 1"
                @click="pageQuery1.pageindex = 1"
                >首页</el-button
              >
            </el-pagination>
          </td>
          <td>
            <el-pagination
              v-model:current-page="pageQuery1.pageindex"
              v-model:page-size="pageQuery1.pagesize"
              :page-sizes="[15, 20, 30]"
              :size="size"
              background="true"
              layout="slot,jumper"
              :total="pageQuery1.totalCount"
            >
              <el-button
                :disabled="pageQuery1.pageindex == pageQuery1.totalPage"
                @click="pageQuery1.pageindex = pageQuery1.totalPage"
                >尾页</el-button
              >
            </el-pagination>
          </td>
        </tr>
      </table>
      <template #footer>
        <el-button @click="showProductDialog = false">关闭</el-button>
        <el-button type="primary" @click="onSelectProducts">选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { StorageRed, StorageWrite } from "@/http/axiosHelper";
import type { ComponentSize } from "element-plus";
import { Delete } from "@element-plus/icons-vue";

const router = useRouter();
const size = ref<ComponentSize>("default");

const pageQuery1: any = reactive({
  pageindex: 1,
  pagesize: 15,
  totalCount: "",
  totalPage: "",
});

// 表单数据
const form = reactive({
  orderCode: "",
  inventoryCode: "",
  inventoryType: "",
  warehouseId: "",
  areaId: "",
  positionId: [],
  productId: "",
  batch: "",
  createDate: new Date().toISOString().split("T")[0],
  createUse: Number(localStorage.getItem("id")) || 0,
  createUseName: localStorage.getItem("userName") || "",
  notes: "",
});

const formRef = ref();

// 下拉选项数据
const warehouseList = ref<any[]>([]);

// 明细数据
const detailList = ref<any[]>([]);
const detailSelection = ref<any[]>([]);

// 查询商品表单
const searchForm = ref({
  product_Number: "",
  product_Name: "",
});

// 控制弹窗显示
const showProductDialog = ref(false);
// 商品数据（实际应从接口获取）
const productOptions = ref([]);

// 选中的商品
const selectedProducts = ref<any[]>([]);

onMounted(() => {
  // 生成盘点单号
  generateInventoryCode();

  // 加载基础数据
  loadWarehouseList();
});

// 生成盘点单号
function generateInventoryCode() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, "0");
  form.inventoryCode = `PD${year}${month}${day}${random}`;
}

// 加载仓库列表
function loadWarehouseList() {
  StorageRed({
    url: "/api/Warehouse/GetWarehouseList",
    method: "get",
  }).then((res: any) => {
    if (res.data && res.data.data) {
      warehouseList.value = res.data.data;
    }
  });
}

// 删除产品行
function removeProduct(index: any) {
  detailList.value.splice(index, 1);
  ElMessage.success("删除成功！");
}

// 获取商品列表
function fetchProductOptions() {
  showProductDialog.value = true;
  StorageRed({
    url: "/api/Reporting_losses/GetProductByWarehouse_InOrOut",
    method: "get",
    params: {
      product_Number: searchForm.value.product_Number,
      product_Name: searchForm.value.product_Name,
      pageindex: pageQuery1.pageindex,
      pagesize: pageQuery1.pagesize,
    },
  }).then((res) => {
    productOptions.value = res.data.data;
    pageQuery1.totalCount = res.data.totalCount;
    pageQuery1.totalPage = res.data.totalPage;
  });
}

// 商品选择变化
function handleSelectionChange(val: any[]) {
  selectedProducts.value = val.map((item) => ({ ...item })); // 深拷贝
}

// 批量添加到盘点明细表格
function onSelectProducts() {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning("请先选择要添加的产品");
    return;
  }

  // 生成统一批次号
  const batchCode = generateBatchCode();

  // 添加所有选中的产品到表格（不进行重复过滤）
  detailList.value.push(
    ...selectedProducts.value.map((row) => ({
      productNumber: row.product_Number,
      productName: row.product_Name,
      specifications: row.specifications,
      batch: batchCode, // 自动生成批次号
      systemQuantity: row.unit_Name,
      positionName: row.warehouse_Name + ":" + row.storage_Name,
      inventory: 0, // 库存数量，用户可编辑
      stocktaking_Count: 0, // 盘点数量，用户可编辑
      productId: row.product_Id,
      warehouse_InOrOutId: row.id,
      warehouse_ID: row.warehouse_ID,
    }))
  );

  ElMessage.success(`成功添加${selectedProducts.value.length}个产品`);

  // 重置状态
  showProductDialog.value = false;
  selectedProducts.value = [];
}

// 明细选择变化
function handleDetailSelectionChange(val: any[]) {
  detailSelection.value = val;
}

// 提交表单
function onSubmit() {
  if (!form.inventoryType) {
    ElMessage.warning("请选择盘点类型！");
    return;
  }

  if (detailList.value.length === 0) {
    ElMessage.warning("请添加盘点明细！");
    return;
  }

  // 构建批量添加的数据结构
  const items = detailList.value.map((item: any) => ({
    stocktakingCode: form.inventoryCode,
    stocktakingType: form.inventoryType,
    location: item.positionName,
    productId: item.productId,
    orderCode: form.orderCode || "",
    batch: item.batch,
    inventory: Number(item.inventory) || 0, // 库存数量，用户输入
    stocktaking_Count: Number(item.stocktaking_Count) || 0, // 盘点数量，用户输入
    notes: form.notes || "",
    warehouse_ID: item.warehouse_ID,
    warehouse_InOrOutId: item.warehouse_InOrOutId,
  }));

  const submitData = {
    items: items,
  };

  StorageWrite({
    url: "/api/Stocktakings/CreateStocktaking",
    method: "post",
    data: submitData,
  }).then((res: any) => {
    if (res.data.code == 200) {
      ElMessage.success(res.data.msg);
      router.push("/StocktakingView");
    } else {
      ElMessage.error(res.data.msg);
    }
  });
}

// 取消
function onCancel() {
  ElMessageBox.confirm("确定要取消吗？未保存的数据将丢失。", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    router.push("/InventoryCheckView");
  });
}

// 生成批次号
function generateBatchCode() {
  const date = new Date();
  const year = date.getFullYear().toString().slice(-2); // 取年份后两位
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let randomStr = "";
  for (let i = 0; i < 3; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return `PD${year}${month}${day}${randomStr}`; // 格式：PD + 年月日 + 3位随机字符
}

// 监听分页变化
watch(pageQuery1, () => {
  if (showProductDialog.value) {
    fetchProductOptions();
  }
});
</script>

<style scoped>
.inventory-check-add-view {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.form-header {
  margin-bottom: 20px;
}

.form-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.main-form {
  margin-bottom: 30px;
}

.custom-select {
  width: 100%;
}

.custom-select >>> .el-input__inner {
  font-weight: bold;
  color: #409eff;
  border-radius: 6px;
  border: 1.5px solid #409eff;
  background: #f8fbff;
  transition: border-color 0.2s;
}

.custom-select >>> .el-input__inner:focus {
  border-color: #66b1ff;
  box-shadow: 0 0 4px #b3d8ff;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.detail-actions .el-button {
  margin-left: 8px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 100px;
}
</style>
